// 非生产性开支
<template>
    <div class="e-form">
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="新增细项明细" name="budgetList" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag">
                </el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form :model="formData" label-width="220px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="项目编号：">
                                            <span>{{formData.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="项目名称：">
                                            <span>{{formData.projectName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="工程类别：">
                                            <span>{{formData.projectTypeName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入人：">
                                             <span>{{formData.recorder}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="编制机构：">
                                            <span>{{formData.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{statusLable(formData.state)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="备注：">
                                            <span>{{formData.remark}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 新增细项明细  -->
                    <div id="budgetListCon" class="con">
                        <div class="tabs-title" id="budgetList">新增细项明细</div>
                        <div class="bigBox">
                            <div class="top">
                                <div class="left">
                            <el-radio-group v-model="structure" @change="changeStructure">
                                <span>查看范围：</span>
                                <el-radio label="0">新增项</el-radio>
                                <el-radio label="1">全部</el-radio>
                            </el-radio-group>
                                </div>
                                <div class="right">
                                <el-input placeholder="输入细目编码细目名称" size="small" v-model="keyWord">
                                    <img @click="searchData" class="searchImg"  src="@/assets/search.png" slot="suffix" />
                                </el-input>
                                </div>
                            </div>
                        </div>
                        <div class="e-tree-table" >
                            <el-table key="a"
                                class="table"
                                :data="budgetListTable"
                                border
                                style="width: 100%"
                                row-key="listId"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                            >
                                <el-table-column label="操作" min-width="100" align='left'>
                                </el-table-column>
                                <el-table-column prop="structureNo" label="序号" min-width="200">
                                </el-table-column>
                                 <el-table-column prop="structureName" label="构造类别" min-width="200">
                                </el-table-column>
                                <el-table-column prop="structureType" label="构造类型" min-width="200" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span>{{ setCurrentStructureType(scope.row.structureType)}}</span>
                                </template>
                                </el-table-column>
                                <el-table-column prop="libStructureName" label="结构名称" min-width="200">
                                </el-table-column>
                                <el-table-column prop="codeNo" label="细目编号" width="150">
                                </el-table-column>
                                <el-table-column prop="codeName" label="细目名称" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                                <el-table-column prop="qty" label="工程数量" min-width="200" show-overflow-tooltip>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="billId" isView bucketName="project" />
                    </div>

                     <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                @getAuditHistory="getAuditHistory"
                                billType='PartFirstChange'
                                ref="AuditHistoryRef"
                                :tableData.sync="auditHistoryTable"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                class="btn-blue"
                v-if="statusLable(state) !== '草稿'"
                size="small"
                v-debounce
                >打印</el-button
            >
            <ComExaButtons :auditState="auditState" @exas="exas"
            :founderId="formData.founderId" :state="formData.state"/>
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
import request from '@/api/projectManagement/divisionOfStructuralParts.js'
import { getCurrentUnitInfo, audit, nullify, undoworkt, history } from '@/api/projectManagement/audit.js'
import { openAppClient, hideLoading, showLoading } from '@/utils/common'
import ComExaButtons from '@/components/common/exaButtons'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            auditHistoryTable: [], //审核历史表格
            formData: {
              	'billId': '',
                'orgId': '',
                'orgName': '',
                'profileId': '',
                'projectName': '',
                'projectNo': '',
                'projectType': '',
                'projectTypeName': '',
                'recorder': '',
                'recorderId': '',
                'remark': '',
                'state': 0
            },
            budgetListTable: [], //新增细项明细
            auditState: {}, //流程按钮显示状态
            //历史审核
            auditParams: {
                'isPass': true,
                'opinion': '',
                'isShareInAudit': true,
                'freeNextUser': '',
                'freeNextUnitIndex': 0,
                'billId': this.$route.query.billId,
                'billType': 'StructureListChange'
            },
            //作废参数
            nullifyParams: {
                'billId': this.$route.query.billId,
                'billType': 'StructureListChange',
                'nullifyReason': '',
                'nullifyDescription': ''
            },
            //按钮状态参数
            auditHistoryParams: {
                'billId': this.$route.query.billId,
                'billType': 'StructureListChange'
            },
            //明细参数
            detailedParmes: {
                billId: '',
                keyWord: '',
                parentId: '0',
                rang: '1'
            },
            //搜索关键字
            keyWord: '',
            //划分预览维度
            structure: '1'
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj ? obj.label : ''
            }
        },
        billId () {
            return this.$route.query.billid || this.$route.query.billId
        },
        //当前单据状态
        state () {
            return this.formData.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        //当前构造类别
        setCurrentStructureType () {
            return type=>{
                const obj = {
                    0: '单位工程',
                    1: '子单位工程',
                    2: '分部工程',
                    3: '子分部工程',
                    4: '分项工程',
                    5: '子分项工程',
                    6: '桩号'
                }
                return obj[type]
            }
        }
    },
    components: {
        ComExaButtons,
        AttachComp,
        ComAuditHistoryIndex,
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'budgetList', 'attach']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getBaseInfo(),
                this.getListInfo(),
                this.getCurrentUnitInfo(),
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取基本信息
        getBaseInfo () {
            request.getStandardListInfoData({ billId: this.billId }).then(res=>{
                this.formData = res
            })
        },
        //获取明细
        getListInfo () {
            this.detailedParmes.billId = this.billId
            this.detailedParmes.rang = this.structure
            request.getStandardListDetailedData(this.detailedParmes).then(res=>{
                this.budgetListTable = this.listConversionTree(res, '0')
            })
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditHistoryParams).then(res => {
                console.log(res, 'res')
                this.auditState = res
            })
        },
        //取消
        handleClose () {
            //this.$router.replace('/leaseAcceptanceList')
        },
        //===============审核=================
        async exas (arg) {
            if (arg === 'audit') {
                this.setAuditParams(this.auditParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    audit(auditParams).then(() => {
                        this.clientPop('suc', '审核成功', this.handleClose)
                    })
                })
            } else if (arg === 'undoAudit') {
                undoworkt(this.auditHistoryParams).then(() => {
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
            }else if (arg === 'nullify') {
                this.setAuditParams(this.nullifyParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/nullifyDialog', '单据作废原因', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    nullify(auditParams).then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                })
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditHistoryParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //将请求回来的数组转为树
        listConversionTree (arr, parentId) {
            const tree = []
            let temp
            for (let i = 0; i < arr.length; i++) {
                if (arr[i].parentId == parentId) {
                    const obj = arr[i]
                    temp = this.listConversionTree(arr, arr[i].listId)
                    if (temp.length > 0) {
                        obj.children = temp
                    }
                    tree.push(obj)
                }
            }
            return tree
        },
        //变更预览维度
        changeStructure () {
            this.detailedParmes.parentId = '0'
            this.getListInfo()
        },
        //搜索
        searchData () {
            this.detailedParmes.parentId = '0'
            this.detailedParmes.keyWord = this.keyWord
            this.getListInfo()
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}
.e-table {
    background: #fff;
}
.e-tree-table{
    background: #fff;
 }
.mainTitle{
    box-sizing: border-box;
    width:100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246,246,246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.box{
    width: 90px;
    height: 55px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
.box:hover{
    background: rgb(205,205,205);
    border-radius: 8px;
}
.icon{
    width: 30px;
    height: 30px;
}
.iconFont{
    font-size: 14px;
}
.bigBox {
    padding: 0 10px;
    .top {
        margin: 0 auto;
        background: #fff;
        display: flex;
        justify-content: space-between;
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 5px;
        box-shadow: 1px 1px 5px rgba(201, 198, 198, 0.804);
        .left {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .right {
            margin-left: 20px;
        }
    }
}
</style>
